<?php

namespace app\admin\controller;

use app\admin\service\GoodsRuleService;
use app\model\goods\GoodsRuleTpl;
use support\Request;
use support\View;

class goodsRuleController extends Curd
{


    public function index(Request $request)
    {

        if (request()->isAjax()) {

            $goodsRuleService = new GoodsRuleService();
            $res = $goodsRuleService->getList($request->all());
            return $this->success($res);
        }
        return view('goods_rule/index');
    }

    /**
     * 添加
     */
    public function add(Request $request)
    {
        if (request()->isAjax()) {

            $param = $request->post();

            $goodsRuleService = new GoodsRuleService();
            $res = $goodsRuleService->addGoodsRule($param);
            return $this->success($res);
        }
        return view('goods_rule/add');
    }

    /**
     * 编辑
     */
    public function edit(Request $request)
    {
        if (request()->isAjax()) {

            $param = $request->post();

            $goodsRuleService = new GoodsRuleService();
            $res = $goodsRuleService->editGoodsRule($param);
            return $this->success($res);
        }

        $id = $request->input('id');
        $goodsRuleModel = new GoodsRuleTpl();
        $info = $goodsRuleModel->findOne([
            'id' => $id
        ])['data'];

        $first = [];
        $left = [];
        $itemNum = 0;

        if (!empty($info['value'])) {
            $value = json_decode($info['value'], true);
            $first = $value[0];
            unset($value[0]);
            $left = $value;
            $itemNum = count($value);
        }

        View::assign([
            'first' => $first,
            'left' => $left,
            'info' => $info,
            'itemNum' => $itemNum
        ]);

        return view('goods_rule/edit');
    }


    /**
     * 删除
     */
    public function del(Request $request)
    {
        $id = $request->input('id');

        $goodsRuleModel = new GoodsRuleTpl();
        $info = $goodsRuleModel->delById($id);
        return $this->success($info);
    }

    /**
     * 获取规格信息
     */
    public function getRuleByGoodsId(Request $request)
    {
        $id = $request->input('goods_id');

        $goodsRuleService = new GoodsRuleService();
        $res = $goodsRuleService->getRuleByGoodsId($id);
        return json($res);
    }

}